class QuestionList
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  belongs_to :competition
  belongs_to :author, class_name: "User", inverse_of: :question_lists

  field :name, type: String
  field :published, type: Boolean, default: false
  field :vote, type: Boolean, default: false

  has_many :questions, order: :created_at.asc, dependent: :destroy
  has_one :topic, autobuild: true, dependent: :destroy, as: :topic_container

  belongs_to :section

  scope :published_lists, ->(current_user) {
    any_of( { published: true }, {author: current_user} )
  }
  scope :not_finished_lists, ->(current_user) {
    where( published: false,  :author.ne =>  current_user )
  }

  after_save do |doc|
    if doc.topic.new_record?
      doc.topic.save
    end
  end

  def commit_suggestion(qv)
    q = Question.new
    q.question_list = self
    q.save
    qv.question = q
    qv.save
  end

  def clone_from(question)
    qv = question.current_version.clone_without_relations
    q = Question.new
    qv.question = q
    qv.author = self.author
    qv.created_at = nil
    q.question_list = self
    qv.save
    q.save
  end

  def set_vote
    self.update_attributes(vote: true)
    self.questions.each do |q|
      q.current_version.vote.save
    end
  end
end
